﻿namespace AuSys.Services.App.FileStorage.Specific
{
    public class LocalStorage : IFileStorage
    {
        private readonly string _domainName;
        private readonly string _storeRootPath;
        public StorageProvideType ProvideType => StorageProvideType.Stream;

        private const string configReadFailedMsg = "本地文件存储：配置异常";
        public LocalStorage(LocalStorageConfig config)
        {
            _storeRootPath = config.StoreRootPath
                ?? throw new Exception(configReadFailedMsg);
            _domainName = config.DomainName
                ?? throw new Exception(configReadFailedMsg);
            DirectoryInfo di = new(_storeRootPath);
            if(!di.Exists) { di.Create(); }
        }
        public bool Save(Stream s, string pathName, out string? errmsg)
        {
            try
            {
                string path = Path.Combine(_storeRootPath, pathName);
                string dirPath = Path.GetDirectoryName(path)
                    ?? throw new Exception("保存文件：路径异常");
                DirectoryInfo dirInfo = new(dirPath);
                if(!dirInfo.Exists) { dirInfo.Create(); }
                var fs = File.Create(path);
                s.CopyTo(fs);
                s.Flush();
                s.Close();
                fs.Close();
            }
            catch (Exception ex)
            {
                errmsg = ex.Message;
                return false;
            }
            errmsg = null;
            return true;
        }
        public bool Delete(string pathName, out string? errmsg)
        {
            FileInfo f = new(Path.Combine(_storeRootPath, pathName));
            if(f.Exists)
                f.Delete();
            errmsg = null;
            return true;
        }
        public string FullUrl(string pathName)
        {
            var rightPart = FileStorageConsts.ActionRouteOf(pathName);
            return $"{_domainName}{rightPart}";
        }
        public Stream? Read(string pathName)
        {
            try
            {
                var fs = File.OpenRead(Path.Combine(_storeRootPath, pathName));
                return fs;
            }
            catch
            {
                return null;
            }
        }
    }
    public class LocalStorageConfig
    {
        public string? DomainName { get; set; }
        public string? StoreRootPath { get; set; }
    }
}
